package com.mvc.business.service;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

import com.mvc.base.service.BaseCompanyManager;
import com.mvc.base.service.SupplierManager;
import com.mvc.business.model.Schedule;
import com.mvc.framework.dao.HibernateWebUtils;
import com.mvc.framework.model.CommonAuditableEntity;
import com.mvc.framework.util.PageSearch;

/**
 * 
 * @author snowpbx
 * @version V1.0 Create Time: 2012-12-2
 */
@Service
public class ScheduleManager extends BaseCompanyManager<Schedule, Integer> {

	@Autowired
	private SupplierManager	supplierManager;

	public Schedule get(Serializable id) {
		Schedule order = super.get(id);
		if (order != null) {
			order.setSupplier(supplierManager.getByObjectId(order.getSupplierId()));
		}
		return order;
	}

	public List<Schedule> getSchedulesByPurchaseId(Integer purchaseId) {
		return searchBySql("select A from " + Schedule.class.getName() + " A where A.recStatus=? and purchaseId=?", new Object[] {
		        CommonAuditableEntity.REC_STATUS_VALID, purchaseId });
	}

	public void find(final PageSearch page, boolean my) {
		getHibernateTemplate().execute(new HibernateCallback<PageSearch>() {
			public PageSearch doInHibernate(Session session) {
				Criteria criteria = HibernateWebUtils.createCriteria(session, page.getEntityClass(), page.getFilters());
				if (0 == page.getTotalCount()) {
					criteria.setProjection(Projections.rowCount());
					Object object = criteria.uniqueResult();
					int total = object == null ? 0 : ((Number) object).intValue();
					page.setTotalCount(total);
				}
				addOrder(page, criteria);
				criteria.setProjection(null);
				List items = criteria.setFirstResult(page.getBegin()).setMaxResults(page.getPageSize()).list();
				page.setList(items);
				return page;
			}
		});
	}

}
